import httplib, os

global progress; progress = 0.0
global cancel; cancel = 0

def post_multipart(host, selector, fields, files):
	"""
	Post fields and files to an http host as multipart/form-data.
	fields is a sequence of (name, value) elements for regular form fields.
	files is a sequence of (name, filename, value) elements for data to be uploaded as files
	Return the server's response page.
	"""
	BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
	h = httplib.HTTP(host)
	h.putrequest('POST', selector)
	h.putheader('content-type','multipart/form-data; boundary=%s' % BOUNDARY)
	h.putheader('content-length', str(38 + sum(81 + len(name) + len(value) for name,value in fields) + sum(134 + len(name) + len(filename) + os.path.getsize(filepath) for name,filename,filepath in files)))
	h.endheaders()
	encode_multipart_formdata(h, BOUNDARY, fields, files, 1024)
	global cancel
	if cancel: 
		cancel = 0
		return "Canceled"
	errcode, errmsg, headers = h.getreply()
	return h.file.read()

def encode_multipart_formdata(L, BOUNDARY, fields, files, dataread):
	"""
	L: an http connection.
	BOUNDARY is a BOUNDARY (DUH!).
	fields: a sequence of (name, value) elements for regular form fields.
	files: a sequence of (name, filename, value) elements for data to be uploaded as files
	dataread: the length of each block to read from file
	"""
	CRLF = '\r\n'
	global cancel
	#if cancel: 
	#	cancel = 0
	#	return
	for (key, value) in fields:
		if cancel: 
			break
		L.send('--' + BOUNDARY) # 2 + 2 + len(BOUNDARY)
		L.send(CRLF)
		L.send('Content-Disposition: form-data; name="%s"' % key) # 2 + 39 + len(key)
		L.send(CRLF)
		L.send(CRLF)
		L.send(value) # 2 + len(value)
		L.send(CRLF)
	for (key, filename, value) in files:
		if cancel: 
			break
		fp = file(value,"rb")
		size = os.path.getsize(value)
		L.send('--' + BOUNDARY)
		L.send(CRLF)
		L.send('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
		L.send(CRLF)
		L.send('Content-Type: %s' % get_content_type(filename))
		L.send(CRLF)
		L.send(CRLF)
		#L.send(value)
		print '[multipart] * Reading %s in blocks of %s bytes' % (value, dataread)
		data = fp.read(dataread)
		global progress
		while (data):
			if cancel:
				print "Upload operation was canceled !!!"
				break
			L.send(data)
			data = fp.read(dataread)
			progress = fp.tell()*100.0/size
			print progress
		L.send(CRLF)
	L.send('--' + BOUNDARY + '--')
	L.send(CRLF)

def get_content_type(filename):
	#return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
	return 'application/octet-stream'
